<?php defined('SYSPATH') or die('No direct script access.');

/**
 * @file post.php
 * @brief post管理
 * @author Lionel Tsai
 * @version 1.0
 * @date 2012-02-17
 */
class Controller_Post extends Controller_Rest {
	public function before()
	{
		parent::before();
	}
	
	/**
	 * @brief 获取post
	 *
	 * @param $post_id
	 *
	 * @return $this
	 */
	public function action_get($post_id=NULL)
	{
		if($post_id)
		{
			$this->get_post($post_id);
		}
		else
		{
			$this->get_posts();
		}
	}
	
	/**
	 * @brief 获取指定post
	 *
	 * @param $post_id
	 *
	 * @return $this
	 */
	private function get_post($post_id)
	{
		$post = ORM::factory('post', $post_id);
		if(!$post->ID)
		{
			$this->response->body('指定文章不存在！')->status(206);
			return;
		}
		$res = json_encode($post->as_array());
		$this->response->body($res)->status(200);
	}
	
	/**
	 * @brief 获取指定起止位置的post
	 *
	 * @return $this 
	 */
	private function get_posts()
	{
		/** 获取起止数*/
		$start = filter_input(INPUT_GET, 'start', FILTER_VALIDATE_INT);
		$pos = filter_input(INPUT_GET, 'pos', FILTER_VALIDATE_INT);

		/** 获取文章状态，包含inherit、publish、private、draft*/
		$status = filter_input(INPUT_GET, 'post_status');
		/** 获取文章类型，包含post表示为已发布的文章，revision表示为修订版本，page为页面*/
		$type = filter_input(INPUT_GET, 'post_type');
		/** 获取指定文章日期*/
		$date = filter_input(INPUT_GET, 'post_date');
		
		$status = ($status) ? $status : 'publish';
		$type = ($type) ? $type :'post';

		$post = ORM::factory('post');
		$start = ($start) ? $start : 0;
		$pos = ($pos) ? $pos : PHP_INT_MAX;

		if($date)
		{/** 获取规定时间内的post*/
			$posts = $post
				->where('post_status','=',$status)
				->and_where('post_type','=',$type)
				->and_where('post_date','=',$date)
				->offset($start)
				->limit($pos)
				->find_all();
		}
		else
		{/** 获取所有时间内的post*/
			$posts = $post
					->where('post_status','=',$status)
					->and_where('post_type','=',$type)
					->offset($start)
					->limit($pos)
					->find_all();
		}

		if(!$posts->count())
		{
			$this->response->body('不存在相应的文章！')->status(202);
			return;
		}
		else
		{
			$res['num'] = $posts->count();
			$res['list'] = array();
			foreach($posts as $pst)
			{
				$res['list'][] = $pst->as_array();
			}
			$json_res = json_encode($res);
			$this->response->body($json_res)->status(200);
		}
	}
	
	/**
	 * @brief 新增post
	 *
	 * @return $this
	 */
	public function action_post()
	{
		$post = ORM::factory('post');
		if(!$_POST)
		{
			$this->response->body('请提交相应post内容！')->status('206');
			return;
		}
		if(isset($_POST['ID']))
		{
			unset($_POST['ID']);
		}
		try 
		{
			$new_post = $this->request->post();
			$post_author = $new_post['post_author'];
			if($post_author)
			{
				$user = ORM::factory('user',$post_author);
				if(!$user->id) 
				{
					$this->response->body('post_author not exist!')->status(206);
					return;
				}
			}
			$post->values($_POST)->check()->save();
			$this->response->body('"'.$_POST['post_title'].'" add success!')->status(200);
		}
		catch(ORM_Validation_Exception  $e)
		{
			$errors = $e->errors();
			foreach($errors as $k=>$v)
			{
				$this->response->body($k.':not available')->status(206);
			}
		}
	}
	
	/**
	 * @brief 更新post
	 *
	 * @param $post_id
	 *
	 * @return $this
	 */
	public function action_put($post_id)
	{
		$post = ORM::factory('post',$post_id);

		if(!$post->ID)
		{
			$this->response->body('no post available!')->status(206);
			return;
		}
		$new_post = $this->request->post();
		try
		{
			if($new_post)
			{
				$post_author = (isset($_POST['post_author'])) ?  $new_post['post_author'] : 0;

				/** if author exist*/
				if($post_author)
				{
					$user = ORM::factory('user',$post_author);
					if(!$user->id) 
					{
						$this->response->body('post_author not exist!')->status(206);
						return;
					}
				}
				
				$post->values($new_post)->check()->update();
				$this->response->body('update success!')->status(200);
			}
			else
			{
				$this->response->body('json data not exists!')->status(202);
			}
		}
		catch(ORM_Validation_Exception $e)
		{
			/** 验证错误*/
			$error = $e->errors();
			foreach($error as $k => $v)
			{
				$this->response->body($k.':not available')->status(206);
			}
		}
		catch(Exception $err)
		{
			$this->response->body($err->getMessage())->status(500);
		}
	}
	
	/**
	 * @brief 删除指定post
	 *
	 * @param $post_id
	 *
	 * @return $this
	 */
	public function action_delete($post_id)
	{
		$post = ORM::factory('post', $post_id);
		if(!$post->ID)
		{
			$this->response->body('post not exist')->status(206);
			return;
		}
		try
		{
			/** 删除相应post下所有的postmeta*/
			$postmeta=$post->postmeta->find_all();
			$query = DB::delete('postmeta')->where('post_id','=',$post_id);
			$query->execute();
			//$postmeta->delete();

			/** delete post*/
			$post->delete();

			$this->response->body('post-'.$post_id.' delete success!')->status(200);
		}
		catch(Exception $err)
		{
			$this->response->body($err->getMessage())->status(500);
		}
	}
}
